import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import App from './App.vue'
import './style.css'

/**
 * Vue子应用入口文件
 * @description 初始化Vue应用并集成qiankun生命周期
 */

// 创建Vue应用实例
let app = null
let router = null

// 渲染应用
const render = (props = {}) => {
  const { container } = props
  
  // 创建路由实例
  router = createRouter({
    history: createWebHistory(window.__POWERED_BY_QIANKUN__ ? '/vue-app' : '/'),
    routes: [
      {
        path: '/',
        name: 'Home',
        component: () => import('./views/Home.vue')
      },
      {
        path: '/products',
        name: 'Products',
        component: () => import('./views/Products.vue')
      },
      {
        path: '/orders',
        name: 'Orders',
        component: () => import('./views/Orders.vue')
      }
    ]
  })

  // 创建应用实例
  app = createApp(App)
  
  // 注册Element Plus图标
  for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
  }
  
  // 使用插件
  app.use(router)
  app.use(ElementPlus)
  
  // 挂载应用
  const targetContainer = container ? container.querySelector('#app') : document.getElementById('app')
  app.mount(targetContainer)
}

// 独立运行时
if (!window.__POWERED_BY_QIANKUN__) {
  render()
}

// qiankun生命周期
export async function bootstrap() {
  console.log('Vue子应用启动')
}

export async function mount(props) {
  console.log('Vue子应用挂载', props)
  render(props)
}

export async function unmount(props) {
  console.log('Vue子应用卸载', props)
  const { container } = props
  const targetContainer = container ? container.querySelector('#app') : document.getElementById('app')
  app.unmount(targetContainer)
  app = null
  router = null
}

export async function update(props) {
  console.log('Vue子应用更新', props)
} 